<template>
  <div>
    <div class="head">
      <div class="input">
        <span>题目内容：</span>
        <el-input v-model="queryData.title" clearable placeholder="请输入" />
      </div>
      <div class="input">
        <span>题目类型：</span>
        <el-select v-model="queryData.type" clearable placeholder="请选择题目类型">
          <el-option label="单选" :value="1">单选</el-option>
          <el-option label="多选" :value="2">多选</el-option>
          <el-option label="判断" :value="3">判断</el-option>
        </el-select>
      </div>
      <div class="input">
        <span>培训类型：</span>
        <el-cascader
          :show-all-levels="false"
          :options="options2"
          v-model="queryData.selected_type_ids"
          :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
          clearable
        ></el-cascader>
      </div>
      <el-button type="primary" class="btn" @click="search">查询</el-button>
      <el-button type="primary" class="btn" @click="reset">重置</el-button>
      <el-button type="primary" class="btn" @click="add">新增试题</el-button>
      <a :href="downUrl" style="margin: 0px 10px"><el-button type="primary" class="btn">下载模板</el-button></a>
      <el-upload action="#" :show-file-list="false" accept=".xlsx,.xls" :http-request="handleImport">
        <el-button class="btn" type="primary">导入</el-button>
      </el-upload>
    </div>
    <div class="box">
      <el-table
        :data="tableData"
        border
        v-loading="isTableLoading"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        style="width: 100%"
        :max-height="tableHeight"
      >
        <el-table-column fixed type="index" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="题目内容" min-width="240" />
        <el-table-column prop="type" align="center" label="题目类型" width="140">
          <template #default="scope">
            {{ scope.row.type | getType }}
          </template>
        </el-table-column>
        <el-table-column
          prop="options"
          align="center"
          show-overflow-tooltip
          label="题目选项"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="answer" align="center" label="题目答案" width="140"></el-table-column>
        <el-table-column prop="type_name" align="center" label="培训类型" width="140"> </el-table-column>
        <el-table-column fixed="right" align="center" prop="action" label="操作" width="160">
          <template #default="scope">
            <div class="action">
              <span @click="detail(scope.row)">详情</span>
              <span @click="edit(scope.row)">编辑</span>
              <span @click="delOk(scope.row)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 5px; text-align: right"
        @size-change="search"
        @current-change="getList"
        :current-page.sync="queryData.page"
        :page-size.sync="queryData.size"
        layout="total, prev, pager, next,sizes,jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <span>确定删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delOk">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="addTitle" :visible.sync="isShowAdd" width="1000px" :before-close="handleClose" :close-on-click-modal="false">
      <el-form
        ref="addData"
        :model="addData"
        style="width: 100%"
        :rules="addRules"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训类型" prop="selected_type_ids">
              <el-cascader
                :show-all-levels="false"
                :options="options2"
                style="width: 100%"
                v-model="addData.selected_type_ids"
                :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
                clearable
                :disabled="isDetail"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目类型" prop="type">
              <el-radio-group :disabled="isDetail" v-model="addData.type">
                <el-radio :label="1">单选题</el-radio>
                <el-radio :label="2">多选题</el-radio>
                <el-radio :label="3">判断题</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题目内容" prop="title">
              <el-input
                :disabled="isDetail"
                type="textarea"
                :autosize="{ minRows: 4 }"
                placeholder="请输入题目内容"
                v-model="addData.title"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项A" prop="a">
              <el-input :disabled="isDetail" placeholder="请输入" v-model="addData.a"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项B" prop="b">
              <el-input :disabled="isDetail" placeholder="请输入" v-model="addData.b"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项C" prop="c">
              <el-input :disabled="isDetail" placeholder="请输入" v-model="addData.c"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项D" prop="d">
              <el-input :disabled="isDetail" placeholder="请输入" v-model="addData.d"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项E" prop="e">
              <el-input :disabled="isDetail" placeholder="请输入" v-model="addData.e"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项F" prop="f">
              <el-input :disabled="isDetail" placeholder="请输入" v-model="addData.f"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目答案" prop="answer">
              <el-select
                v-model="addData.answer"
                placeholder="请选择"
                multiple
                :multiple-limit="addData.type == 2 ? 4 : 1"
                style="width: 100%"
                :disabled="isDetail"
              >
                <el-option label="选项A" value="A">选项A</el-option>
                <el-option label="选项B" value="B">选项B</el-option>
                <el-option label="选项C" value="C">选项C</el-option>
                <el-option label="选项D" value="D">选项D</el-option>
                <el-option label="选项E" value="E">选项E</el-option>
                <el-option label="选项F" value="F">选项F</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题目解析" prop="desc">
              <div ref="editorContainer" id="editorContainer" style="width: 100%"></div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="" prop="options">
          <el-form-item
            :prop="'options.' + index + '.value'"
            :rules="{
              required: true,
              message: '请输入选项内容',
              trigger: 'blur',
            }"
            v-for="(item, index) in addData.options"
            :key="index"
          >
            <div class="add_option">
              <span class="add_option_a">选项{{ getABC(index) }}</span>
              <el-input :disabled="isDetail" placeholder="请输入" v-model="item.value" style="width: 400px"></el-input>
              <el-button
                style="margin-left: 10px"
                type="danger"
                size="mini"
                @click="delOption(index)"
                v-if="addData.options.length > 2 && !isDetail"
                >删除</el-button
              >
            </div>
          </el-form-item>
          <el-button v-if="addData.options.length < 6 && !isDetail" @click="addOption">添加选项</el-button>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button v-if="!isDetail" type="primary" @click="submitForm('addData')">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { dateFormat } from '../../libs/util';
import { TopicSave, TopicList, TrainTypeTree, TopicDelete, TopicInfo, upload, TopicUpload } from '@/api/manage';
import E from 'wangeditor';
const ABC = ['A', 'B', 'C', 'D', 'E', 'F'];
export default {
  name: 'cultivate',
  filters: {
    getType(type) {
      switch (type) {
        case 1:
          return '单选';
        case 2:
          return '多选';
        case 3:
          return '判断';
        default:
          return '';
      }
    },
  },
  data() {
    return {
      downUrl: process.env.VUE_APP_API_URL + 'template/topic_template.xlsx',
      tableHeight: 500,
      addTitle: '添加题目',
      queryData: {
        name: '',
        type: '',
        page: 1,
        size: 10,
        selected_type_ids: [],
        type_ids: [],
        ids: [],
        create_type: 2,
        resource_type: 1, // 1公共资源
      },
      total: 0,
      isTableLoading: false,
      tableData: [],
      dialogVisible: false,
      isShowAdd: false,
      addData: {},
      addRules: {
        type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
        selected_type_ids: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
        title: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入题目解析', trigger: 'blur' }],
        answer: [{ required: true, message: '请选择题目答案', trigger: 'change' }],
        a: [{ required: true, message: '请输入选项A', trigger: 'blur' }],
        b: [{ required: true, message: '请输入选项B', trigger: 'blur' }],
      },
      options2: [],
      isEdit: false,
      isDetail: false,
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 260;
    });
    this.getList();
    this.getTrainTypeTree();
  },
  watch: {
    'queryData.selected_type_ids'(newValue, oldValue) {
      if (this.queryData.selected_type_ids.length > 0) {
        this.queryData.type_ids = [];
        this.queryData.selected_type_ids.forEach((item) => {
          this.queryData.type_ids.push(item[item.length - 1]);
        });
      } else {
        this.queryData.type_ids = [];
      }
    },
  },
  methods: {
    handleImport(e) {
      let obj = new FormData();
      obj.append('file', e.file);
      obj.append('create_type',2);
      obj.append('resource_type',this.queryData.resource_type);
      TopicUpload(obj).then((res) => {
        this.$message.success('导入成功');
        this.getList();
      });
    },
    handleClose() {
      this.addData = {};
      this.isShowAdd = false;
      this.isEdit = false;
      this.isDetail = false;
      this.item = null;
    },
    getInfo() {
      TopicInfo({ id: this.item.id }).then((res) => {
        this.addData = res.data.data;
        this.addData.answer = JSON.parse(this.addData.answer);
        this.isShowAdd = true;
        this.$nextTick(() => {
          this.init();
        });
      });
    },
    getABC(index, label) {
      return label ? label + ABC[index] : ABC[index];
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let typeArr = [];
          this.addData.selected_type_ids.forEach((item) => {
            typeArr.push(item[item.length - 1]);
          });
          this.addData.resource_type = 1; // 1公共资源
          let ruleForm = {
            ...this.addData,
            type_ids: typeArr,
            create_type: 2,
          };
          TopicSave(ruleForm).then((res) => {
            this.$message.success(this.addData.id ? '修改成功' : '添加成功');
            this.handleClose();
            this.getList();
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    search() {
      this.queryData.page = 1;
      this.getList();
    },
    reset() {
      this.queryData.title = '';
      this.queryData.type = '';
      this.queryData.selected_type_ids = [];
      this.queryData.type_ids = [];
      this.queryData.exclude_ids = [];
      this.search();
    },
    edit(item, type) {
      this.addTitle = '编辑试题';
      this.item = item;
      this.isEdit = true;
      this.getInfo();
      // this.$router.push({
      //   path: '/enterprise/testDetails/index',
      // });
    },
    detail(item) {
      this.addTitle = '试题详情';
      this.item = item;
      this.isDetail = true;
      this.getInfo();
    },
    del(item) {
      this.dialogVisible = true;
      this.item = item;
    },
    delOk(item) {
      this.$confirm('确定删除该试题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        TopicDelete({ id: item.id }).then((res) => {
          this.$message.success('删除成功');
          this.item = null;
          this.getList();
          this.dialogVisible = false;
        });
      });
    },
    add() {
      this.addTitle = '添加试题';
      this.isShowAdd = true;
      this.addData = {
        type: 1,
        title: '',
        selected_type_ids: [],
        type_ids: [],
        desc: '',
        answer: [],
      };
      this.$nextTick(() => {
        this.init();
      });
    },
    getList() {
      this.isTableLoading = true;
      TopicList(this.queryData).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.isTableLoading = false;
      });
    },
    getTrainTypeTree() {
      TrainTypeTree().then((res) => {
        this.options2 = res.data.list;
      });
    },
    init() {
      if (this.phoneEditor) {
        if (this.isDetail || this.isEdit) {
          this.phoneEditor.txt.html(this.addData.desc);
        } else {
          this.phoneEditor.txt.html('');
        }
        if (this.isDetail) {
          this.phoneEditor.disable();
        } else {
          this.phoneEditor.enable();
        }
        return;
      }
      this.phoneEditor = new E('#editorContainer');
      // 上传图片到服务器，base64形式
      this.phoneEditor.config.excludeMenus = ['video', 'code'];
      this.phoneEditor.config.uploadImgShowBase64 = true;
      // // 隐藏网络图片
      this.phoneEditor.config.showLinkImg = false;

      this.phoneEditor.config.debug = true;
      //图片上传接口
      this.phoneEditor.config.uploadImgServer = process.env.VUE_APP_API_URL + 'enterprise/upload'; // 上传图片的接口地址
      this.phoneEditor.config.uploadFileName = 'file'; // formdata中的name属性，比如现在是将图片image加入到formdate，后台从image中接收到图片数据
      this.phoneEditor.config.uploadImgHeaders = {
        token: sessionStorage.getItem('token'), // 设置请求头
      };
      this.phoneEditor.config.withCredentials = true;
      this.phoneEditor.config.uploadImgHooks = {
        customInsert: (insertImg, result, editor) => {
          console.log('成功', result);
        },
      };
      this.phoneEditor.config.customUploadImg = (resultFiles, insertImgFn) => {
        let formObj = new FormData();
        formObj.append('file', resultFiles[0]);
        upload(formObj).then((res) => {
          insertImgFn(res.data.url);
        });

        // 上传图片，返回结果，将图片插入到编辑器中
      };
      // 创建一个富文本编辑器
      this.phoneEditor.create();
      // 修改的时候，需要富文本内容回显，则需要加入以下代码
      if (this.isDetail || this.isEdit) {
        this.phoneEditor.txt.html(this.addData.desc);
      }
      if (this.isDetail) {
        this.phoneEditor.disable();
      } else {
        this.phoneEditor.enable();
      }

      this.phoneEditor.config.onchange = (html) => {
        this.addData.desc = html; // 绑定当前逐渐地值
        // this.$emit('change', this.info_); // 将内容同步到父组件中
      };
    },
  },
};
</script>

<style scoped>
.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  background: #ffffff;
  border-radius: 5px;
  padding: 20px;
  padding-bottom: 0px;
}
.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}
.input > span {
  font-size: 12px;
  flex-shrink: 0;
}
.btn {
  margin-bottom: 20px;
}
.box {
  width: 100%;
  background: #ffffff;
  border-radius: 5px;
  padding: 20px;
  margin-top: 20px;
}
.action {
  display: flex;
  align-items: center;
  justify-content: center;
}
.action span {
  color: #0256ff;
  font-size: 12px;
  cursor: pointer;
  margin: 0 8px;
}
.add_option {
  width: 100%;
  display: flex;
  align-items: center;
  /* margin-bottom: 20px; */
}
.add_option_icon {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: 1px solid #ccc;
  margin-right: 10px;
}
.add_option_a {
  font-size: 12px;
  margin-right: 20px;
}
#editorContainer /deep/ .w-e-text-container {
  height: 300px !important;
}
</style>
